package com.edu.robot.core.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.edu.chat.facade.facade.RecallFacade;
import com.edu.chat.facade.model.dto.RecallResDTO;
import com.edu.chat.facade.model.request.RecallReq;
import com.edu.robot.core.enums.IntentEnum;
import com.edu.robot.core.enums.NotifyMsgEnum;
import com.edu.robot.core.model.APICallback;
import com.edu.robot.core.model.KnowledgeResult;
import com.edu.robot.core.model.SessionContext;
import com.edu.robot.modules.robot.dto.ModelConfigDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

/**
 * @program: KQAIA
 * @description: 知识库意图识别处理类
 * @author: 无恙
 * @create: 2025-03-26 21:00
 **/

@Component("knowledgeModelProcess")
@Slf4j
public class KnowledgeModelProcess extends AbstractModelInvoke {

	@DubboReference(interfaceClass = RecallFacade.class, check = false)
	private RecallFacade recallFacade;

	@Autowired
	private ChatModelProcess chatModelProcess;


	@Override
	public void buildModel(SessionContext sessionContext) {
		//设置模型参数
		ModelConfigDTO modelConfigDTO = new ModelConfigDTO();
		modelConfigDTO.setModelName("qwen-max");
		sessionContext.setModelConfigDTO(modelConfigDTO);
	}

	@Override
	public void buildPrompt(SessionContext sessionContext) {
		// 使用更清晰的变量命名
		final String systemPromptTemplate = IntentEnum.INTENT_KNOWLEDGE.getSysPrompt();
		final String tenantId = sessionContext.getTenantId();
		final String question = sessionContext.getQuestion();


		// 构造请求参数对象
		RecallReq recallReq = new RecallReq();
		recallReq.setContent(question);
		recallReq.setTenantId(tenantId);
		recallReq.setPrivateLibraryIds(sessionContext.getPrivateKnowledgeId());
		recallReq.setPublicLibraryIds(sessionContext.getPublicKnowledgeId());
		recallReq.setSceneId(sessionContext.getSceneId());
		recallReq.setSessionId(sessionContext.getSessionId());

		// 方法调用结果使用更有意义的变量名
		List<RecallResDTO> knowledgeItems = recallFacade.recall(recallReq);
		log.info("KnowledgeModelProcess recall res: {}", knowledgeItems);

		// 构建知识库内容
		String knowledgeContent = buildKnowledgeContent(knowledgeItems);

		// 格式化最终提示
		String formattedPrompt = String.format(systemPromptTemplate, knowledgeContent);

		sessionContext.setPrompt(formattedPrompt);
	}


	@Override
	public String invokeModel(SessionContext sessionContext) {
		final String finalAnswer = modelManger.modelInvoke(sessionContext);

		KnowledgeResult knowledgeResult = JSONUtil.toBean(finalAnswer, KnowledgeResult.class);
		APICallback callback = sessionContext.getCallback();

		//1，判断本次回复是否有效,如果无效，返回模型的引导语句
		if (!knowledgeResult.getValid()){

			callback.onEvent(NotifyMsgEnum.NORMAL,knowledgeResult.getAnswer());
			callback.close(knowledgeResult.getAnswer());

			return finalAnswer ;
		}

		log.info("KnowledgeModelProcess invokeModel data:{}",finalAnswer);

		//2，有效
		callback.onEvent(NotifyMsgEnum.NORMAL,knowledgeResult.getAnswer());
		callback.close(knowledgeResult.getAnswer());
		sessionContext.setAgentAnswer(knowledgeResult.getAnswer());
//		return chatModelProcess.invokeFallback(sessionContext);
		return knowledgeResult.getAnswer();
	}

	/**
	 * 构建知识库内容字符串
	 */
	private String buildKnowledgeContent(List<RecallResDTO> knowledgeItems) {
		if (CollectionUtil.isEmpty(knowledgeItems)) {
			return "没有相关知识";
		}

		StringBuilder contentBuilder = new StringBuilder(256); // 根据典型内容长度初始化容量
		for (RecallResDTO item : knowledgeItems) {
			// 使用安全的空值处理
			String source = Optional.ofNullable(item.getSource()).orElse("");
			String sourceId = Optional.ofNullable(item.getSourceId()).orElse("");
			String content = Optional.ofNullable(item.getContent()).orElse("");

			// 使用系统无关的换行符并优化格式化
			contentBuilder.append(String.format("%s&%s: %s%n", source, sourceId, content));
		}
		return contentBuilder.toString().trim(); // 去除最后的多余换行
	}
}
